package com.whc.gulimall.order.interceptor;

import cn.hutool.http.server.HttpServerRequest;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author angaoen
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest httpRequest = this.getHttpServletRequestSafely();
        if (null != httpRequest && null != httpRequest.getAttribute("X-Request-No")) {
            template.header("X-Request-No", httpRequest.getAttribute("X-Request-No").toString());
        }

    }

    public HttpServletRequest getHttpServletRequestSafely() {
        try {
            RequestAttributes requestAttributesSafely = this.getRequestAttributesSafely();
            return requestAttributesSafely instanceof NonWebRequestAttributes
                    ? null : ((ServletRequestAttributes) requestAttributesSafely).getRequest();
        } catch (Exception var2) {
            return null;
        }

    }

    public RequestAttributes getRequestAttributesSafely() {
        RequestAttributes requestAttributes;

        try {
            requestAttributes = RequestContextHolder.currentRequestAttributes();
        } catch (IllegalStateException var3) {
            requestAttributes = new NonWebRequestAttributes();
        }

        return requestAttributes;
    }

}
